package handlers;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
//import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;



@SuppressWarnings("unused")
public class XMLHandler extends DefaultHandler implements DocumentHandler{

	private StringBuffer elementBuffer = new StringBuffer();
	private HashMap<String, String> attributeMap;
	private Document doc;
	
	public Document getDocument(InputStream is) throws Exception{
		SAXParserFactory spf = SAXParserFactory.newInstance();
	try {
			SAXParser parser = spf.newSAXParser();
			//parser.parse(f, this);
			parser.parse(is, this);
	}
	catch (IOException e) {
		throw new Exception("Cannot parse XML document", e);
	}
	catch (ParserConfigurationException e) {
		throw new Exception("Cannot parse XML document", e);
	}
	catch (SAXException e) {
		throw new Exception("Cannot parse XML document", e);
	}
	return doc;
	
	}
	
	public void startDocument() {
		doc = new Document();
	}
	
	@SuppressWarnings("unchecked")
	public void startElement(String uri, String localName,String qName, Attributes atts) throws SAXException {
		elementBuffer.setLength(0);
		//attributeMap.clear();
		if (atts.getLength() > 0) {
			attributeMap = new HashMap();
			for (int i = 0; i < atts.getLength(); i++) {
				attributeMap.put(atts.getQName(i), atts.getValue(i));
			}
		}
	}
	
	// called when cdata is found
	public void characters(char[] text, int start, int length) {
		elementBuffer.append(text, start, length);
	}
	
	// called at element end
	@SuppressWarnings({ "deprecation" })
	public void endElement(String uri, String localName, String qName)	throws SAXException {
//		if (qName.equals("address-book")) {
//			return;
//		}
//		else if (qName.equals("contact")) {
//			Iterator iter = attributeMap.keySet().iterator();
//			while (iter.hasNext()) {
//				String attName = (String) iter.next();
//				String attValue = (String) attributeMap.get(attName);
//				//doc.add(Field.Keyword(attName, attValue));
//				doc.add(new Field(attName, attValue, Field.Store.YES,Field.Index.TOKENIZED));
//			}
//		}
//		else {
			//doc.add(Field.Keyword(qName, elementBuffer.toString()));
			doc.add(new Field(qName, elementBuffer.toString(), Field.Store.YES,Field.Index.TOKENIZED));
//		}
	}
	
	
}
